<?php
/**
 * 《采购明细》实现类
 *
 * @author 孙晓晔
 * @version $Id: Apply.class.php 839 2010-01-07 12:36:26Z xuy $
 */
require_once(dirname(__FILE__) . '/Purchase.class.php');

class RecordIn extends Purchase {
	public $tbl = Constant::tbl_wl_record_in;

	public $type = array(
		'-' => '请选择',
		'1' => '含税价格',
		'2' => '不含税价格',
	);

	public $orderby = array(
		'-' => '请选择',
		'mold' => '产品',
			
		'name' => '名称',
		'standard' => '规格',
	
		'category' => '大类',
		'subclass' => '小类',
		
		'price' => '单价',
			
		'emp' => '采购员',
		'1' => '创建时间',
		'2' => '更新时间',
	);

	public $groupby = array(
		'-' => '请选择',		
		
		'emp' => '采购员',
		'supplier' => '供应商',
		'currency' => '币种',
		'mold' => '产品',

		'status' => '状态',
		'2' => '日期',
		'3' => '月份',
	);

	function __construct() {
		$request['update'] = '$Date: 2009/02/16 07:36:07 $';
		$request['revision'] = '$Revision: 1.1 $';

		parent::__construct($request);
	}

	function pretreat($controller) {
		parent::pretreat($controller);

		$controller->assign_by_ref('type_option', $this->type);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function find($controller, $request) {
		$this->pretreat($controller);

		$controller->assign('t1', strtotime('-3 month'));
		
		$emp = array(
			// '-' => '请选择',
			'emp' => '采购员',
			'oper' => '录入员',
		);
		
		$controller->assign_by_ref('emp_option', $emp);

		$controller->display($request, 'material/in/record/find');
		return true;
	}

	function _orderby_x($controller, $row, $px) {
		$orderby = $this->orderby['1'];
		$row['orderby_x'] = $row['createtime'];

		if (empty($px) || $px == '-' || $px == '1') {
			$controller->assign('orderby', $orderby);

			return $row;
		}

		if ($px == '2') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['modifytime'];
		}

		if ($px == 'category') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['category'];
		}

		if ($px == 'subclass') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['subclass'];
		}

		$controller->assign('orderby', $orderby);

		return $row;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function bom($controller, $request) {
		$this->pretreat($controller);

		$bom_s = $request['bom_s'];
		$bom = $this->id(Constant::tbl_material_bom, $bom_s);

		$material_s = $bom['material'];
		$standard_s = $bom['standard'];

		$db = newdb($this->dsn_r);
		$sql = "SELECT * FROM " . $this->tbl;
		$where = " WHERE material = '" . $material_s . "' AND standard LIKE '%" . $standard_s . "%' ORDER BY id DESC LIMIT 20";
		$sql .= $where;
		debug($sql);
		$result = $db->query($sql);
		$data = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);

			$row['p'] = $this->id(Constant::tbl_wl_purchase, $row['purchase']);

			$row = $this->_orderby_x($controller, $row, $this->orderby_s);

			$data[] = $row;
		}
		$controller->assign_by_ref('result', $data);

		$controller->display($request, 'material/in/record/bom');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function xls($controller, $request) {
		$this->pretreat($controller);

		$this->findPara($controller, $request);

		$request['tpl'] = "xls";
		
		$dd = sprintf(" AND %s = '%s'", "DATE_FORMAT(a.createtime, '%Y-%m')", date('Y-m', strtotime($request['t1_s'])));

		require_once(dirname(__FILE__) . '/Purchase.class.php');
		$aa = new Purchase();
		
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a %s %s";
		$where = $this->_where($request);
		
		$orderby = $this->_orderby();		
		$sql = sprintf($fmt, $this->tbl, $where, $orderby);
		debug($sql);

		$result = $db->query($sql);
		$data = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);
			
			$row['purchase_x'] = $aa->_view($row['purchase']);
			
			$row = $this->_orderby_x($controller, $row, $this->orderby_s);

			$data[] = $row;
		}
		$controller->assign_by_ref('result', $data);
		
		$filename = sprintf("%s.xls", date("YmdHis"));
		header('Content-Disposition:application/vnd.ms-excel; filename=' . $filename);

		$controller->display($request, 'material/in/record/list');
		return true;
	}

	function _where($request) {
		$material_s = $this->_input($request['material_s']);

		$supplier_s = $this->_input($request['supplier_s']);
		
		$category_s = $request['category_s'];
		$subclass_s = $request['subclass_s'];

		$purchase_s = $this->_input($request['purchase_s']);

		$name_s = addslashes(trim($request['name_s']));
		$standard_s = addslashes(trim($request['standard_s']));
		
		$emp_t_s = $request['emp_t_s'];
		if ($emp_t_s == 'emp') {
			$request['emp_s'] = $request['emp_a_s'];
		} else if ($emp_t_s == 'oper') {
			$request['oper_s'] = $request['emp_a_s'];
		}

		$my = $this->_my();

		if (empty($my)) {
			$where = " WHERE 1=1";
		} else {
			$where = " WHERE " . $my;
		}
	

		if (!empty($purchase_s)) {
			$where .= " AND purchase = '" . $purchase_s . "'";
		}

		if (!empty($material_s)) {
			$where .= " AND material = '" . $material_s . "'";
		}

		if (!empty($category_s) && $category_s <> '-') {
			$where .= " AND category = '" . $category_s . "'";
		}

		if (!empty($subclass_s) && $subclass_s <> '-') {
			$where .= " AND subclass = '" . $subclass_s . "'";
		}

		if (!empty($name_s)) {
			$where .= " AND (name LIKE '%" . $name_s . "%' OR content LIKE '%" . $name_s . "%')";
		}
		
		if (!empty($standard_s)) {
			$where .= " AND standard LIKE '%" . $standard_s . "%'";
		}

		$where .= $this->_where_default($request);
		$where = $this->_where_aa($where);

		return $where;
	}
	
	function _my() {
		if ($this->_is_admin()) {
			return '';
		}
	
		if ($this->_audit('60') || $this->_audit('68')) {
			return '';
		}
	
		$emp = $_SESSION['id'];
	
		return sprintf(" (emp = '%s' OR oper = '%s')", $emp, $emp);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function findPost($controller, $request) {
		$this->pretreat($controller);

		$this->findPara($controller, $request);

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a %s %s";
		$where = $this->_where($request);
		$orderby = $this->_orderby();
		$sql = sprintf($fmt, $this->tbl, $where, $orderby);
		debug($sql);

		$pager_option = array (
            'db' => $db,
            'sql' => $sql,
            'PageSize' => $this->pagesize,
            'CurrentPageID' => $request['p'],
            'numItems' => $request['n']
		);

		$pager = @new Pager($pager_option);
		$data = $pager->getPageData();

		if ($pager->number > 0) {
			$count = 0;
			$from = $pager->from;
			while ($count < $pager->number) {
				$row = $data[$count];
				$row = $this->_view(null, $row);

				$row = $this->_orderby_x($controller, $row, $this->orderby_s);

				$row['is_delete'] = $this->_is_delete($row);

				$data[$count] = $row;
				$count++;
			}
			$controller->assign_by_ref('result', $data);
			$controller->assign_by_ref('pager', $pager);
		}

		$controller->display($request, 'material/in/record/list');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function edit($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'material/in/record/edit');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function editPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];

		$purchase = $this->_input($request['purchase']);
		$mold = $this->_input($request['mold']);

		$name = addslashes($request['name']);
		$standard = addslashes($request['standard']);

		// 入库单位
		$amount = $request['amount'];
		$unit = $request['unit'];

		// 采购单位
		$amount2 = $request['amount2'];
		$unit2 = $request['unit2'];
		$price2 = $request['price2'];
		
		$total = $request['total'];
		if (empty($total)) {
			$total = $amount2 * $price2;
		}		

		$tax = $request['tax'];
		$currency = $request['currency'];

		$pay = $total / $amount;
		$price = $pay * pow(10, 2) / (100 + $tax);

		$content = addslashes($request['content']);

		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET purchase = '%s', mold = '%s', name = '%s', standard = '%s', amount = '%s', unit = '%s', currency = '%s', price = '%s', tax = '%s', pay = '%s'";
		$fmt .= ", amount2 = '%s', unit2 = '%s', price2 = '%s', total = '%s', content = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $purchase, $mold, $name, $standard, $amount, $unit, $currency, $price, $tax, $pay, $amount2, $unit2, $price2, $total, $content, $id);
		debug($sql);
		$db->query($sql);
		
		$totals = $this->_total($purchase);
		
		require_once(dirname(__FILE__) . '/Purchase.class.php');
		$aa = new Purchase();
		$aa->_update_total($purchase, $totals);

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function amount2($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'material/in/record/amount2');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function amount2Post($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		
		clean($this->tbl . "_id_" . $id);
		$row = $this->id($this->tbl, $id);
				
		$amount = $row['amount'];
		
		$amount2 = $request['amount2'];		
		$total = $amount2 * $row['price2'];
		$tax = $row['tax'];

		$pay = $total / $amount;
		$price = $pay * pow(10, 2) / (100 + $tax);

		$content = addslashes($request['content']);

		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET price = '%s', pay = '%s', amount2 = '%s', total = '%s', content = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $price, $pay, $amount2, $total, $content, $id);
		debug($sql);
		$db->query($sql);
		
		$totals = $this->_total($row['purchase']);
		
		require_once(dirname(__FILE__) . '/Purchase.class.php');
		$aa = new Purchase();
		$aa->_update_total($row['purchase'], $totals);

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	function view($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'material/in/record/view');
		return true;
	}
	
	function _view($id = 0, $row = null) {
		if ($row == null) {
			clean($this->tbl . "_id_" . $id);
			$row = $this->id($this->tbl, $id);
		}
		
		if (empty($row['total'])) {
			$row['total'] = $row['price2'] * $row['amount2'];
		}			
		
		$row = $this->_view_t($row);
		
		$row['mold_'] = $row['mold'] . ":" . $row['mold_t'];
		
		return $row;
	}
	
	function delete($controller, $request) {
		$this->pretreat($controller);
	
		$db = newdb($this->dsn);
		while (list($k, $id) = each($request)) {
			if (substr($k, 0, 2) <> "c_") {
				continue;
			}
	
			$row = $this->id($this->tbl, $id);
			if ($this->_is_delete($row)) {
	
				$fmt = "DELETE FROM %s WHERE id = '%s'";
				$sql = sprintf($fmt, $this->tbl, $id);
				// debug($sql);
				$db->query($sql);
			}
		}
	
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));
	
		$this->findPost($controller, $request);
		return true;
	}
	
	function _delete($id) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $id);
		$result = $db->query($sql);
		// debug($sql);
		if ($row = $db->fetch_array($result)) {
			if ($row['status'] < 3 && $row['oper'] == $_SESSION['id']) {
				return false;
			}
	
			return true;
		}
	
		return true;
	}
	
	function _count($field = 'purchase', $id, $status = 'all') {
	
		$db = newdb($this->dsn_r);
		if ($status == 'all') {
			$fmt = "SELECT COUNT(*) t FROM %s WHERE `%s` = '%s' AND visible = '1' ORDER BY id";
			$sql = sprintf($fmt, $this->tbl, $field, $id);
		} else {
			$fmt = "SELECT COUNT(*) t FROM %s WHERE `%s` = '%s' AND visible = '1' AND status = '%s' ORDER BY id";
			$sql = sprintf($fmt, $this->tbl, $field, $id, $status);
		}
		debug($sql);
		$result = $db->query($sql);
		$row = $db->fetch_array($result);
	
		return $row['t'];
	}
	
	function _total($id) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT SUM(price2*amount2) t FROM %s WHERE purchase = '%s' AND visible = '1'";
		$sql = sprintf($fmt, $this->tbl, $id);
		debug($sql);
		$result = $db->query($sql);
		$row = $db->fetch_array($result);
		
		return $row['t'];
	}
	
	function _total2($field = 'purchase', $id, $status = 'all') {
	
		$db = newdb($this->dsn_r);
		if ($status == 'all') {
			$fmt = "SELECT SUM(price2*amount2) t FROM %s WHERE `%s` = '%s' AND visible = '1' ORDER BY id";
			$sql = sprintf($fmt, $this->tbl, $field, $id);
		} else {
			$fmt = "SELECT SUM(price2*amount2) t FROM %s WHERE `%s` = '%s' AND visible = '1' AND status = '%s' ORDER BY id";
			$sql = sprintf($fmt, $this->tbl, $field, $id, $status);
		}
		debug($sql);
		$result = $db->query($sql);
		$row = $db->fetch_array($result);
	
		return $row['t'];
	}
	
	function _list($id, $status = 'all') {
		$db = newdb($this->dsn_r);
		if ($status == 'all') {
			$fmt = "SELECT * FROM %s WHERE purchase = '%s' AND visible = '1' ORDER BY id";
			$sql = sprintf($fmt, $this->tbl, $id);
		} else {
			$fmt = "SELECT * FROM %s WHERE purchase = '%s' AND visible = '1' AND status = '%s' ORDER BY id";
			$sql = sprintf($fmt, $this->tbl, $id, $status);
		}		
		// debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);
			
			$s = $this->_print_content($row['content']);
			if ($row['unit'] <> $row['unit2']) {
			// if ($row['type'] <> '1' || $row['unit'] <> $row['unit2']) {
				
				$row['content'] = sprintf("%s%s %s", floatval($row['amount']), $row['unit'], $s);
				// $row['content'] = sprintf("%s%s", floatval($row['amount']), $row['unit']);
			} else {
				$row['content'] = $s;
			}

			if ($row['type'] == '3') {
				$row['standard'] = sprintf("%s%s", "ф", $row['standard']);
			} else {
				$row['standard'] = $row['standard'];
			}

			$ret[] = $row;
		}

		return $ret;
	}
	
	function _list2($id, $status = 'all') {
		$db = newdb($this->dsn_r);
		if ($status == 'all') {
			$fmt = "SELECT * FROM %s WHERE purchase = '%s' AND visible = '1' ORDER BY id";
			$sql = sprintf($fmt, $this->tbl, $id);
		} else {
			$fmt = "SELECT * FROM %s WHERE purchase = '%s' AND visible = '1' AND status = '%s' ORDER BY id";
			$sql = sprintf($fmt, $this->tbl, $id, $status);
		}		
		// debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);
			
			$row['ok'] = true;			

			$ret[] = $row;
		}

		return $ret;
	}
	
	function _list3($id, $status = 'all') {
		$db = newdb($this->dsn_r);
		if ($status == 'all') {
			$fmt = "SELECT * FROM %s WHERE receive = '%s' AND visible = '1' ORDER BY id";
			$sql = sprintf($fmt, $this->tbl, $id);
		} else {
			$fmt = "SELECT * FROM %s WHERE receive = '%s' AND visible = '1' AND status = '%s' ORDER BY id";
			$sql = sprintf($fmt, $this->tbl, $id, $status);
		}
		// debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);
				
			$s = $this->_print_content($row['content']);
			if ($row['unit'] <> $row['unit2']) {
				// if ($row['type'] <> '1' || $row['unit'] <> $row['unit2']) {
	
				$row['content'] = sprintf("%s%s %s", floatval($row['amount']), $row['unit'], $s);
				// $row['content'] = sprintf("%s%s", floatval($row['amount']), $row['unit']);
			} else {
				$row['content'] = $s;
			}
	
			if ($row['type'] == '3') {
				$row['standard'] = sprintf("%s%s", "ф", $row['standard']);
			} else {
				$row['standard'] = $row['standard'];
			}
	
			$ret[] = $row;
		}
	
		return $ret;
	}
		
	function _update($request) {
		
		$id = $request['id'];
		
		$emp = $this->_input($request['emp']);
		$office = $this->_office($emp);
		$dept = $this->_emp_dept($emp);
		 
		$supplier = $this->_input($request['supplier']);
		 
		$currency = $request['currency'];
		$rate = $this->_exchange($currency);
		$tax = $request['tax'];
		 
		$data = json_decode($request['item'], true);
		
		$db = newdb($this->dsn_w);	
		debug(print_r($log, true));	
		while (list($k, $v) = each($data)) {
			
			$mold = $this->_input($v['mold_']);
			$name = addslashes($v['name']);
			$standard = addslashes($v['standard']);
			$content = addslashes($v['content']);
			
			if (empty($name) && empty($mold)) {
				continue;
			}
			
			$amount = $v['amount'];
			$total = $v['total'];
			
			$pay = $total / $amount;
			$price = $pay * pow(10, 2) / (100 + $tax);
				
			if (array_key_exists("createtime", $v)) {
				if ($v['status'] > 7) {
					continue;
				}
				
				clean($this->tbl . "_id_" . $v['id']);
				
				if (!$this->_ok($v['ok'])) {
					$fmt = "UPDATE %s SET visible = '2', modifytime = now() WHERE id = '%s'";
					$sql = sprintf($fmt, $this->tbl, $v['id']);
				} else {					
					$fmt = "UPDATE %s SET mold = '%s', name = '%s', standard = '%s', amount2 = '%s', unit2 = '%s', price2 = '%s', total = '%s', ";
					$fmt .= "amount = '%s', unit = '%s', price = '%s', pay = '%s', content = '%s', modifytime = now() WHERE id = '%s'";
					$sql = sprintf($fmt, $this->tbl, $mold, $name, $standard, $v['amount2'], $v['unit2'], $v['price2'], $total, $amount, $v['unit'], $price, $pay, $content, $v['id']);
				}			
			} else {
				if (!$this->_ok($v['ok'])) {
					continue;
				}
			
				$fmt = "INSERT INTO %s(`purchase`, mold, name, standard, amount2, unit2, price2, total, amount, unit, price, pay, content, oper, createtime, modifytime)";
				$fmt .= " VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', now(), now())";
				$sql = sprintf($fmt, $this->tbl, $id, $mold, $name, $standard, $v['amount2'], $v['unit2'], $v['price2'], $total, $amount, $v['unit'], $price, $pay, $content, $_SESSION['id']);			
			}
			
			debug($sql);
			$db->query($sql);
		}
		
		$fmt = "UPDATE %s SET emp = '%s', supplier = '%s', currency = '%s', rate = '%s', tax = '%s', rmb = price2 * rate WHERE `purchase` = '%s'";
		$sql = sprintf($fmt, $this->tbl, $emp, $supplier, $currency, $rate, $tax, $id);
		debug($sql);
		$db->query($sql);
	}
	
	function _update_supplier($request) {
		// $id, $supplier, $currency, $tax
		
		$id = $request['id'];
		$emp = $this->_input($request['emp']);
	
		$supplier = $this->_input($request['supplier']);
			
		$currency = $request['currency'];
		$rate = $this->_exchange($currency);
		$tax = $request['tax'];
	
		$db = newdb($this->dsn_w);
		$a = pow(10, -2) * $tax + 1;
		$fmt = "UPDATE %s SET supplier = '%s', currency = '%s', rate = '%s', rmb = '%s', price = pay / %f, tax = '%s' WHERE purchase = '%s'";
		$sql = sprintf($fmt, $this->tbl, $supplier, $currency, $rate, $rmb, $a, $tax, $id);
		debug($sql);
		$db->query($sql);
	
		$fmt = "UPDATE %s SET rmb = price2 * rate WHERE purchase = '%s'";
		$sql = sprintf($fmt, $this->tbl, $id);
		debug($sql);
		$db->query($sql);
		if ($db->affected_rows() > 0) {
			return true;
		}
			
		return false;
	}
	
	function _tax($price, $tax) {
		return $price * (1 + $tax);
	}
	
	function _tax_no($price, $tax) {
		return $price / (1 + $tax);
	}
	
	function view_bom($bom) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE bom = '%s'";
		$sql = sprintf($fmt, $this->tbl, $bom);
		$result = $db->query($sql);
		if ($row = $db->fetch_array($result)) {
			
			return $this->view_purchase($row['purchase']);
		}
		
		return array();
	}
	
	function view_purchase($id) {
		require_once(dirname(__FILE__) . '/Purchase.class.php');
		$aa = new Purchase();
		$ret = $aa->_view($id);
		
		return $ret;
	}
	
	function z($controller, $request) {
		$s = 100;
		
		// echo sprintf("%.2f\n", $s);
		// echo $this->_tax_no($s, 0.17);
		
		echo pow(10, -2) * 17;
		
		logdate($controller, $request);
		return true;
	}

	function status($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$purchase = $request['purchase'];
		clean($this->tbl . "_id_" . $id);

		$status = $request['status'];

		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET status = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $status, $id);
		// debug($sql);
		$db->query($sql);

		if($status == 9) {
			$db = newdb($this->dsn);
			$fmt = "INSERT INTO %s (record, createtime, modifytime) VALUES('%s', now(), now())";
			$sql = sprintf($fmt, Constant::tbl_wl_in, $id);
			$db->query($sql);

			$row = $this->id($this->tbl, $id);
			$this->inamount($row['material'], $row['amount']);
		}

		$db = newdb($this->dsn);
		$fmt = "SELECT status from %s WHERE purchase = '%s' group by status";
		$sql = sprintf($fmt, $this->tbl, $purchase);
		$result = $db->query($sql);
		$len = $db->num_rows($result);
		if($len <= 1) {
			$db = newdb($this->dsn);
			$fmt = "UPDATE %s SET status = '%s', modifytime = now() WHERE id ='%s'";
			$sql = sprintf($fmt, Constant::tbl_wl_purchase, $status, $purchase);
			$db->query($sql);
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	function in($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		require_once 'Purchase.class.php';
		$aa = new Purchase();
		$purchase = $aa->_view($row['purchase']);
		$controller->assign_by_ref('purchase', $purchase);

		// $controller->assign_by_ref('supplier', $this->_supplier($purchase['supplier']));

		$controller->display($request, 'material/in/record/in');
		return true;
	}

	/**
	 * 采购入库
	 */
	function inPost($controller, $request) {
		$this->pretreat($controller);
		
		$id = $request['id'];
		
		$fmt = "SELECT * FROM %s WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $id);
		
		$request['sql'] = $sql;
		
		$this->_in($request);		

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function _in_purchase($request) {
		$id = $request['id'];
		
		$fmt = "SELECT * FROM %s WHERE purchase = '%s' AND status in ('3', '4', '8')";
		$sql = sprintf($fmt, $this->tbl, $id);
		
		$request['sql'] = $sql;
		
		return $this->_in($request);
	}
	
	function _in($request) {
	
		$emp = $this->_input($request['emp']);
		$date = $request['date'];
		$number = $request['number'];
	
		$purchase = $request['purchase'];
		$supplier = $request['supplier'];
	
		$place = $request['place'];
		$content = addslashes($request['content']);
	
		require_once(dirname(__FILE__) . '/Receive.class.php');
		$bb = new Receive();
	
		$receive = $bb->_update($purchase, $supplier, $number, $date, $emp);
	
		require_once(dirname(__FILE__) . '/In.class.php');
		$in = new In();
	
		require_once(dirname(__FILE__) . '/Amount.class.php');
		$aa = new Amount();
	
		require_once(dirname(__FILE__) . '/Bom.class.php');
		$bom = new Bom();
	
		$db = newdb($this->dsn_w);
		$sql = $request['sql'];
		debug($sql);
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$row = $this->_currency($row);

			$amount4 = trim($request['amount4']);
			if (empty($amount4) || $amount4 == 0) {
				$amount4 = $row['amount'] - $row['amount3'];
			}
			
			$amount8 = trim($request['amount3']);
			if (empty($amount8) || $amount8 == 0) {
				$amount8 = $row['amount2'];
			}
	
			$in->_insert($row, $amount4, $amount8, $emp, $date, $receive);
	
			if ($aa->_in_update($row, $amount4, $place, $emp)) {
				$amount3 = $row['amount3'] + $amount4;
				if ($row['amount'] == $amount3) {
					$status = '9';
				} else {
					$status = $row['status'];
				}
	
				$fmt = "UPDATE %s SET amount3 = '%s', content = concat(content, '%s'), status = '%s', modifytime = now() WHERE id = '%s'";
				$sql = sprintf($fmt, $this->tbl, $amount3, $content, $status, $row['id']);
				debug($sql);
				$db->query($sql);
	
				if ($status == '9') {
					if (!empty($row['bom'])) {
						$bom->_update_status($row['bom'], "4");
					}
						
					$this->_purchase_status($row['purchase'], '9');
				}
			} else {
				return false;
			}
		}
	
		return true;
	}
	
	function _returned($purchase, $name, $standard, $amount) {
		$status = '8';
		
		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s WHERE purchase = '%s' AND name = '%s' AND standard = '%s'";
		$sql = sprintf($fmt, $this->tbl, $purchase, $name, $standard);
		debug($sql);
		
		$result = $db->query($sql);
		if ($row = $db->fetch_array($result)) {
			$amount3 = $row['amount3'] - $amount;
			
			$fmt = "UPDATE %s SET amount3 = '%s', status = '%s', modifytime = now() WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $amount3, $status, $row['id']);
			debug($sql);
			$db->query($sql);
			
			
			require_once(dirname(__FILE__) . '/Purchase.class.php');
			$aa = new Purchase();
			
			$aa->_update_status($purchase, '8');
		}
	}
	
	function _currency($row) {
		$c = $row['currency'];
		if ($c == 'CNY' || $c == '-' || empty($c)) {
			return $row;
		}
		
		$d = $this->_exchange($c);
		
		$row['price'] = $row['price'] * $d;
		
		return $row;
	}

	function _purchase_status($id, $status) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE purchase = '%s'";
		$sql = sprintf($fmt, $this->tbl, $id);
		debug($sql);
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			if ($row['status'] <> $status) {
				return false;
			}
		}
		
		require_once 'Purchase.class.php';
		$aa = new Purchase();		
		$aa->_status($id, $status);
	}

	function cancel($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		require_once 'Purchase.class.php';
		$purchase = new Purchase();
		$controller->assign_by_ref('purchase', $purchase->_view($row['purchase']));

		$controller->display($request, 'material/in/record/cancel');
		return true;
	}
	
	function cancelPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);

		$content = addslashes($request['content']);
		$status = $request['status'];

		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET content = concat(content, '%s'), status = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $content, $status, $id);
		// debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return true;
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function back($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);
		
		require_once 'Purchase.class.php';
		$purchase = new Purchase();
		$controller->assign_by_ref('purchase', $purchase->_view($row['purchase']));

		require_once(dirname(__FILE__) . '/../contact/Supplier.class.php');
		$supplier = new Supplier();
		$controller->assign_by_ref('supplier', $supplier->_view($row['supplier']));

		$controller->display($request, 'material/in/record/back');
		return true;
	}

	function backPost($controller, $request) {
		$this->pretreat($controller);		
		
		$id = $request['id'];
		$row = $this->_view($id);
				
		$emp = $this->_input($request['emp']);
		$date = $request['date'];
		
		$place = $request['place'];
		$amount = -1 * floatval($request['amount']);
		
		$b = $row['amount'] + $amount;
		$a = $row['amount2'] * ($b / $row['amount']);
		
		$total = $row['price'] * $b;
		
		$content = addslashes($request['content']);

		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET amount2 = '%s', amount = '%s', total = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $a, $b, $total, $id);
		debug($sql);
		$db->query($sql);
				
		$totals = $this->_total($row['purchase']);
		require_once(dirname(__FILE__) . '/Purchase.class.php');
		$aa = new Purchase();
		$aa->_update_total($row['purchase'], $totals);		

		require_once(dirname(__FILE__) . '/In.class.php');
		$in = new In();
		$in->_insert($row, $amount, $emp, $date);
				
		require_once(dirname(__FILE__) . '/Amount.class.php');
		$bb = new Amount();
		$bb->_update($row, $amount, $place, $emp);	

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function batch_in($controller, $request) {
		$this->pretreat($controller);
	
		$insql = "in ('000000000";
		while (list($k, $v) = each($request)) {
			if (substr($k, 0, 2) == "c_") {
				$insql .= "', '" . $v;
			}
		}
		$insql .= "')";
	
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE id %s";
		$sql = sprintf($fmt, $this->tbl, $insql);
		debug($sql);
	
		$result = $db->query($sql);
		$data = array();
		$purchase = '';
		$supplier = '';
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);
				
			$data[] = $row;
			$purchase = $row['purchase'];
			$supplier = $row['supplier'];
				
			// debug(print_r($row, true));
		}
		$controller->assign_by_ref('record_in', $data);
		
		$controller->assign_by_ref('purchase', $purchase);
		$controller->assign_by_ref('supplier', $supplier);
	
		$controller->display($request, 'material/in/record/batch_in');
		return true;
	}
	
	function batch_inPost($controller, $request) {
		$this->pretreat($controller);
	
		$db = newdb($this->dsn_w);
		while (list($k, $id) = each($request['cc'])) {
			
			$fmt = "SELECT * FROM %s WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $id);
			
			$request['sql'] = $sql;
			
			$this->_in($request);
		}
	
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));
	
		$this->findPost($controller, $request);
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function group($controller, $request) {
		$this->pretreat_group($controller);

		$num = array(
			'1' => '按次数',
			'2' => '按金额',
		);
		$controller->assign('num_option', $num);

		$controller->assign('t1', strtotime('-1 month'));
		// $controller->assign('t2', strtotime('+1 day'));

		$controller->display($request, 'material/in/record/group');
		return true;
	}
	
	function groupby($controller, $px) {
		$px = $this->groupby_aa($px, $this->groupby, 'emp');

		$controller->assign('groupby', $this->groupby[$px]);

		return $this->groupby_dd($px);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function groupPost($controller, $request) {
		$this->pretreat($controller);
			
		$this->groupPara($controller, $request);

		$num_s = $request['num_s'];
		if (!empty($num_s) && $num_s == '2') {
			$fmt = "SELECT %s AS a, SUM(pay*amount) AS c FROM %s a ";
		} else {
			$fmt = "SELECT %s AS a, COUNT(pay) AS c FROM %s a ";
		}
		$sql = sprintf($fmt, $this->s, $this->tbl);

		$where = $this->_where($request);

		$request['sql'] = sprintf("%s %s GROUP BY %s ORDER BY %s %s", $sql, $where, $this->s, $this->orderby, $this->desc);

		$this->_group($controller, $request);

		// $controller->display($request, 'list');
		return true;
	}

	function _name($row, $px) {
		if (empty($px) || $px == '-' || $px == 'emp') {
			$row['a'] = sprintf("%s [%s]", Name::emp($row['a']), $row['a']);
		} elseif ($px == 'material') {
			$row['a'] = Name::material($row['a']);			
		} else {

			$row = $this->_name_t($row, $px);
		}

		return $row;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function cal($controller, $request) {
		$this->pretreat($controller);

		$controller->assign('t1', strtotime('-1 month'));

		$controller->display($request, 'material/bom/cal');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function calPost($controller, $request) {
		$this->pretreat($controller);

		$emp = $this->_input($request['emp']);

		$date1 = $request['date1'];
		$date2 = $request['date2'];

		$content = addslashes($request['content']);

		$where = $this->_cal_where($emp, $date1, $date2);

		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s a, %s b SET a.category = b.category, a.subclass = b.subclass WHERE a.material = b.id %s";
		$sql = sprintf($fmt, $this->tbl, Constant::tbl_material, $where);
		debug($sql);
		$db->query($sql);

		$fmt = "UPDATE %s a SET price_ = price, amount_ = amount WHERE type = 1 %s";
		$sql = sprintf($fmt, $this->tbl, $where);
		debug($sql);
		$db->query($sql);

		$fmt = "SELECT * FROM %s a WHERE type in (2, 3) %s";
		$sql = sprintf($fmt, $this->tbl, $where);
		debug($sql);
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$m = $this->id(Constant::tbl_material, $row['material']);
			$type = $row['type'];
			$standard = $row['standard'];

			if ($type == 2) {
				$v = $this->_v1($standard);
			}

			if ($type == 3) {
				$v = $this->_v2($standard);
			}

			$amount = $v * $m['density'];

			$price = floatval($row['price'] / $amount);

			$fmt = "UPDATE %s SET price_ = '%s', amount_ = '%s' WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $price, $amount, $row['id']);
			debug($sql);
			$db->query($sql);
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	function _cal_where($emp, $date1, $date2) {
		$where = "";
		if (!empty($emp)) {
			$where .= " AND a.emp = '" . $emp . "'";
		}

		if (!empty($date1)) {
			$where .= " AND a.createtime >= '" . $date1 . "'";
		}

		if (!empty($date2)) {
			$where .= " AND a.createtime <= '" . $date2 . "'";
		}

		return $where;
	}

	function t($controller, $request) {
		$db = newdb($this->dsn);
		$fmt = "SELECT * FROM %s";
		$sql = sprintf($fmt, $this->tbl);
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$m = $this->id(Constant::tbl_material, $row['material']);

			$standard = $row['standard'];
			$amount = $row['amount'];
			$type = $row['type'];
			if ($type == '2') {
				$v = $this->_v1($standard);
				if (!empty($m['density']) && $m['density'] > 0) {
					$n = $v * $m['density'];
				} else {
					$n = $v;
				}
					
				$amount2 = $n * $amount;
				$price2 = $row['total'] / $amount2;
			} elseif ($type == '3') {
				$v = $this->_v2($standard);
				if (!empty($m['density']) && $m['density'] > 0) {
					$n = $v * $m['density'];
				} else {
					$n = $v;
				}			
					
				$amount2 = $n * $amount;				
				$price2 = $row['total'] / $amount2;
			} else {
				$price2 = $row['pay'];
				$amount2 = $amount;
			}

			$fmt = "UPDATE %s SET amount2 = '%s', price2 = '%s' WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $amount2, $price2, $row['id']);
			echo $sql . "\n";
			$db->query($sql);

			echo ".";
		}

		logdate($controller, $request);
		return true;
	}	
	
	function f($controller, $request) {
		$s = "23.2";
		
		// echo sprintf("%.2f\n", $s);
		echo $this->_f($s);
		
		logdate($controller, $request);
		return true;
	}
	
	function _f($s) {
		$b = floatval($s);
				
		$a = sprintf("%.2f", $s);
		if ($b == $a) {
			return $a;
		} else {
			$a = sprintf("%.3f", $s);
			if ($b == $a) {
				return $a;
			} else {
				$a = sprintf("%.4f", $s);
			}
		}
		
		return $a;
	}
	
	function sync_price($controller, $request) {
		$df = "DATE_FORMAT(createtime, '%Y-%m-%d')";
		$dd = date("Y-m-d", strtotime("-1 day"));
		
		require_once(dirname(__FILE__) . '/Material.class.php');
		$aa = new Material();
		
		$db = newdb($this->dsn_w);
		$fmt = "SELECT material, max(price2) price FROM %s WHERE %s = '%s' GROUP BY material";
		$sql = sprintf($fmt, $this->tbl, $df, $dd);
		// echo $sql . "\n";
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$aa->_update_price($row['material'], $row['price']);
		}
		
		logdate($controller, $request);
		return true;
	}
	
	function _status_puchase($purchase, $status) {
		$db = newdb($this->dsn_w);
		// $fmt = "UPDATE %s SET status = '%s', modifytime = now() WHERE purchase = '%s' AND status < %s";
		// $sql = sprintf($fmt, $this->tbl, $status, $purchase, $status);
		$fmt = "UPDATE %s SET status = '%s', modifytime = now() WHERE purchase = '%s'";
		$sql = sprintf($fmt, $this->tbl, $status, $purchase);
		$db->query($sql);		
		if ($db->affected_rows() > 0) {
			return true;
		}
			
		return false;
	}
	
	
	
	function _is_po($purchase) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE purchase = '%s'";
		$sql = sprintf($fmt, $this->tbl, $purchase);
		debug($sql);
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			// if ($row['amount'] <= 0 || $row['amount2'] <= 0 || $row['price'] <= 0 || $row['price2'] <=0 ){
			if ($row['amount'] <= 0 || $row['amount2'] <= 0) {
				return false;
			}
		}
		
		return true;
	}
	
	function _insert_bom($id, $purchase, $content) {
		$bom = $this->id(Constant::tbl_material_bom, $id);
		
		$name = addslashes($bom['name']);
		$standard = addslashes($bom['standard']);
		$mold = $bom['mold'];
		
		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s WHERE purchase = '%s' AND name = '%s' AND standard = '%s' AND mold = '%s'";
		$sql = sprintf($fmt, $this->tbl, $purchase, $name, $standard, $mold);
		debug($sql);
		$result = $db->query($sql);
		if ($row = $db->fetch_array($result)) {
			$a = floatval($bom['amount']);
			
			$b = floatval($row['amount']);
			$c = floatval($row['amount2']);
			$d = floatval($row['total']);
			
			$amount = $a + $b;			
			$amount2 = ($amount / $b) * $c;
			$total = ($amount / $b) * $d;
			
			$fmt = "UPDATE %s SET amount = '%s', amount2 = '%s', total = '%s', modifytime = now() WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $amount, $amount2, $total, $row['id']);
			debug($sql);
			$db->query($sql);
			if ($db->affected_rows() > 0) {
				return true;
			}
		} else {
			return $this->_insert($id, $purchase);
		}
		
		return false;
	}
	
	function _insert($id, $purchase) {
		$bom = $this->id(Constant::tbl_material_bom, $id);
		if ($bom) {
			$total = floatval($bom['amount2']) * floatval($bom['price2']);
			
			$name = addslashes($bom['name']);
			$standard = addslashes($bom['standard']);
			$mold = $bom['mold'];
			$content = addslashes($bom['content']);
		} else {
			return false;
		}
	
		$material = $bom['material'];
		$type = $bom['type'];
		
		$amount = $bom['amount'];
		$unit = $bom['unit'];
		$price = $bom['price'];
		
		if (empty($bom['unit2']) || $bom['unit1'] == $bom['unit2']) {
			$amount2 = $amount;
			$unit2 = $unit;
			$price2 = $price;
		} else {
			$amount2 = $bom['amount2'];
			$unit2 = $bom['unit2'];
			$price2 = $bom['price2'];
		}

		$db = newdb($this->dsn_w);
		$fmt = "INSERT INTO %s(purchase, mold, bom, material, type, name, standard, amount, unit, price, amount2, unit2, price2, total, content, oper";
		$fmt .= ", createtime, modifytime) VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', now(), now())";
		$sql = sprintf($fmt, $this->tbl, $purchase, $mold, $id, material, $type, $name, $standard, $amount, $unit, $price, $amount2, $unit2, $price2, $total, $content, $_SESSION['id']);
		debug($sql);
		$db->query($sql);		
		if ($db->affected_rows() > 0) {
			return true;
		}

		return false;
	}
	
	function move($from, $to) {
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET emp = '%s' WHERE emp = '%s' AND status < 8";
		$sql = sprintf($fmt, $this->tbl, $to, $from);
		debug($sql);
		$db->query($sql);
	}
}
?>
